package com.example.chat.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.chat.pojo.User;
import com.google.gson.Gson;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class XingHuoService {

    @Autowired
    private UserService userService;
    private static final String hostUrl = "https://spark-api.xf-yun.com/v4.0/chat";

    @Value("${xinghuo.apiKey}")
    private String apiKey;

    @Value("${xinghuo.apiSecret}")
    private String apiSecret;

    @Value("${xinghuo.appid}")
    private String appid;

    private static final Gson gson = new Gson();
    private static final List<RoleContent> historyList = new ArrayList<>();
    private double totalTokenCost = 0.0;  // 用于累计整个回答的 tokens 消耗

    // 获取鉴权URL
    public String getAuthUrl() throws Exception {
        URL url = new URL(hostUrl);
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());

        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";

        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        String sha = Base64.getEncoder().encodeToString(hexDigits);

        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"",
                apiKey, "hmac-sha256", "host date request-line", sha);

        return Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder()
                .addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)))
                .addQueryParameter("date", date)
                .addQueryParameter("host", url.getHost())
                .build().toString();
    }

    // 向星火API发送请求
    public void sendRequest(String question, WebSocketSession session) throws Exception {
        String authUrl = getAuthUrl();
        OkHttpClient client = new OkHttpClient.Builder().build();
        String wsUrl = authUrl.replace("http://", "ws://").replace("https://", "wss://");

        Request request = new Request.Builder().url(wsUrl).build();
        WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                try {
                    JSONObject requestJson = createRequestJson(question);
                    webSocket.send(requestJson.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                try {
                    handleResponse(text, session);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                t.printStackTrace();
            }
        });
    }

    private JSONObject createRequestJson(String question) {
        JSONObject requestJson = new JSONObject();

        JSONObject header = new JSONObject();
        header.put("app_id", appid);
        header.put("uid", UUID.randomUUID().toString().substring(0, 10));

        JSONObject parameter = new JSONObject();
        JSONObject chat = new JSONObject();
        chat.put("domain", "4.0Ultra");
        chat.put("temperature", 0.5);
        chat.put("max_tokens", 4096);
        parameter.put("chat", chat);

        JSONObject payload = new JSONObject();
        JSONObject message = new JSONObject();
        JSONArray text = new JSONArray();

        for (RoleContent tempRoleContent : historyList) {
            text.add(JSON.toJSON(tempRoleContent));
        }

        RoleContent roleContent = new RoleContent();
        roleContent.setRole("user");
        roleContent.setContent(question);
        text.add(JSON.toJSON(roleContent));
        historyList.add(roleContent);

        message.put("text", text);
        payload.put("message", message);

        requestJson.put("header", header);
        requestJson.put("parameter", parameter);
        requestJson.put("payload", payload);

        return requestJson;
    }
    @Transactional
    public void updateTokens(String username, double totalTokenCost) {

        User user = userService.findByUserName(username);

        if (user == null) {
            System.out.println("User not found for username: " + username);
            throw new RuntimeException("User not found");
        }

        int currentTokens = user.getTokens();
        int updatedTokens = currentTokens - (int) Math.round(totalTokenCost);
        if (updatedTokens < 0) {
            updatedTokens = 0;
        }
        user.setTokens(updatedTokens);
        userService.updateUserTokens(user);
    }

    private StringBuilder answerBuffer = new StringBuilder();
//    private void handleResponse(String text, WebSocketSession session) throws Exception {
//        // 解析 JSON 数据
//        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
//
//        if (myJsonParse.header.code != 0) {
//            System.out.println("Error Code: " + myJsonParse.header.code);
//            return;
//        }
//
//        // 获取片段并将其添加到 answerBuffer
//        List<Text> textList = myJsonParse.payload.choices.text;
//        for (Text temp : textList) {
//            String answerPart = temp.content;
//            answerBuffer.append(answerPart);  // 将片段添加到 StringBuilder 中
//
//            // 计算并累加 token 消耗
//            double tokenCost = calculateTokenCost(answerPart);
//            totalTokenCost += tokenCost;
//
//            System.out.println("Current Token cost: " + tokenCost); // 输出当前片段的 token 消耗（调试用）
//        }
//
//        // 判断是否所有回答片段都已接收完毕
//        if (responseIsComplete(myJsonParse)) {
//            // 当所有片段接收完毕后，发送完整的回答
//            String completeAnswer = answerBuffer.toString();
//            session.sendMessage(new TextMessage(completeAnswer));  // 发送完整的回答给前端
//
//            System.out.println("Complete Answer: " + completeAnswer); // 输出完整的答案到控制台（调试用）
//
//            // 更新 tokens 消耗并重置
//            String username = getUsernameFromSession(session);  // 从 session 中获取用户名
//            updateTokens(username, totalTokenCost);
//            totalTokenCost = 0.0;  // 重置 totalTokenCost
//            answerBuffer.setLength(0);  // 重置 StringBuilder，准备处理下一个回答
//        }
//    }
 private void handleResponse(String text, WebSocketSession session) throws Exception {
    // 解析 JSON 数据
    JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);

    if (myJsonParse.header.code != 0) {
        System.out.println("Error Code: " + myJsonParse.header.code);
        return;
    }

    // 获取片段并将其添加到 answerBuffer
    List<Text> textList = myJsonParse.payload.choices.text;
    for (Text temp : textList) {
        String answerPart = temp.content;
        answerBuffer.append(answerPart);  // 将片段添加到 StringBuilder 中

        // 实时发送当前片段给前端
        session.sendMessage(new TextMessage(answerPart));

        // 计算并累加 token 消耗
        double tokenCost = calculateTokenCost(answerPart);
        totalTokenCost += tokenCost;

        System.out.println("Current Token cost: " + tokenCost); // 输出当前片段的 token 消耗（调试用）
    }

    // 判断是否所有回答片段都已接收完毕
    if (responseIsComplete(myJsonParse)) {
        // 所有片段接收完毕后，可以执行其他操作（如日志记录、资源清理等）
        System.out.println("All parts received. Processing final steps.");

        // 更新 tokens 消耗并重置
        String username = getUsernameFromSession(session);  // 从 session 中获取用户名
        updateTokens(username, totalTokenCost);
        totalTokenCost = 0.0;  // 重置 totalTokenCost
        answerBuffer.setLength(0);  // 重置 StringBuilder，准备处理下一个回答
    }
}


    private String getUsernameFromSession(WebSocketSession session) {
        return (String) session.getAttributes().get("username");
    }
    private double calculateTokenCost(String text) {
        double tokenCost = 0.0;
        int chineseCharCount = 0;
        int englishLetterCount = 0;

        for (char c : text.toCharArray()) {
            if (isChineseCharacter(c)) {
                tokenCost += 0.5; // 中文汉字每个减1.5个tokens
                chineseCharCount++;
            } else if (isEnglishLetter(c)) {
                tokenCost += 0.5; // 英文字母每个减0.8个tokens
                englishLetterCount++;
            }
        }

        return tokenCost;
    }

    private boolean isChineseCharacter(char c) {
        // 判断是否为中文汉字
        return String.valueOf(c).matches("[\\u4E00-\\u9FA5]");
    }

    private boolean isEnglishLetter(char c) {
        // 判断是否为英文字母
        return String.valueOf(c).matches("[a-zA-Z]");
    }

    // 判断是否接收完毕
    private boolean responseIsComplete(JsonParse jsonParse) {
        if(jsonParse.header.status==2){
            return true;
        }
         return false;
    }

    // 内部类定义
    public static class JsonParse {
        Header header;
        Payload payload;
    }

    public static class Header {
        int code;
        int status;
        String sid;
    }

    public static class Payload {
        Choices choices;
    }

    public static class Choices {
        List<Text> text;
    }

    public static class Text {
        String role;
        String content;
    }

    public static class RoleContent {
        private String role;
        private String content;

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}

